<template>
  <div class="trademark">
    <el-card class="box-card">
      <el-button type="primary" icon="plus" @click="addTrademark">添加品牌</el-button>
      <!-- 表格部分 -->
      <el-table style="margin:10px 0;" :data="trademarkList" border>
        <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO" prop="">
          <template #="{row,$index}">
            <img :src="row.logoUrl" alt="logo" title="logo" style="width:60px;height:60px;">
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{row,$index}">
            <el-button type="primary" size="small" icon="edit" @click="editTrademark(row)"></el-button>
            <el-popconfirm :title="`确定要删除${row.tmName}品牌吗?`" @confirm="deleteTrademark(row.id,row.tmName)">
              <template #reference>
                <el-button type="primary" size="small" icon="delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器部分 -->
      <el-pagination v-model:currentPage="paginationData.currentPage" v-model:page-size="paginationData.pageSize" :page-sizes="[3,5,7,9]" :total="paginationData.total" :background="true" layout="prev, pager, next, jumper, ->, sizes, total" @size-change="handlerSizeChange" @current-change="handlerCurrentChange"></el-pagination>
    </el-card>
    <!-- dialog对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="isUpdate==true?'更新品牌信息':'添加品牌'" @close="cancle">
      <el-form :model="dialogFormDate" :rules="rules" ref="formRef" style="width:80%;">
        <el-form-item label="品牌名称" prop="tmName" label-width="110px">
          <el-input v-model="dialogFormDate.tmName" placeholder="输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="110px">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeFileUpload">
            <img v-if="dialogFormDate.logoUrl" :src="dialogFormDate.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="saveOrUpdateTrademark">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElCard, ElButton, ElTable, ElTableColumn, ElPagination, ElDialog, ElForm, ElFormItem, ElInput, ElUpload, ElIcon, ElMessage, ElPopconfirm } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from 'element-plus';
//@ts-ignore
import { reqTrademarkList, reqSaveTrademark, reqPutTrademark, reqRemoveTrademark } from "@/api/product/index.ts";
//@ts-ignore
import { trademarkListData, responseTrademarkListData, saveTrademarkData, responseSaveTrademarkData, responseDeleteTrademarkData } from "@/api/product/type.ts";

import { ref, reactive, onMounted } from "vue";

//dialog对话框开关
let dialogFormVisible = ref(false);
//dialog收集表单数据
let dialogFormDate = reactive<saveTrademarkData>({
  tmName:"",
  logoUrl:"",
  id:0
})
//isUpdate：当前是进行品牌添加还是更新,默认false进行添加操作
let isUpdate = ref(false);
//dialog中的表单校验
let formRef = ref(); //获取表单组件实例
//自定义校验
const validatortmName = (rule:any, value:any, callback:any) => {
  if(value.trim().length >= 2){
    callback();
  } else {
    callback(new Error("品牌名称不能少于两个字符串!"))
  }
}
const validatortLogoUrl = (rule:any, value:any, callback:any) => {
  //图片上传后value为图片地址
  if(value){
    callback();
  }else{
    callback(new Error('品牌logo未上传!'));
  }
}
const rules = {
  tmName:[{ required: true, trigger: 'blur',validator:validatortmName}],
  logoUrl:[{required:true,trigger:'',validator:validatortLogoUrl}]
}

//图片文件上传前的钩子
const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //rawFile.type !== 'image/jpeg'
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == "image/gif") {
    // ElMessage.error('trademark logo must be JPG format!');
    return true;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('trademark logo size can not exceed 2MB!');
    return false
  }
  return true
}
//文件上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  dialogFormDate.logoUrl = URL.createObjectURL(uploadFile.raw!);
  //图片上传成功后，清除掉对应的表单图片项的校验结果
  formRef.value.clearValidate("logoUrl");
}

//生命周期
onMounted(()=>{
  getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
})

//分页器相关数据
let paginationData = reactive({
  currentPage:1,
  pageSize:3,
  total:0,
})
//品牌列表数据
let trademarkList = ref<any>([]);

//获取品牌基本数据列表
const getTrademarkList = async ({page,limit}:trademarkListData) => {
    let res:responseTrademarkListData = await reqTrademarkList({page,limit});
    if(res.code == 200){
      paginationData.total = res.data.total;
      trademarkList.value = res.data.records;
      // console.log("品牌基本数据列表api成功",res);
    }
}

//添加品牌按钮
const addTrademark = () => {
  dialogFormVisible.value = true;
  isUpdate.value = false;
}
//分页器相关回调
const handlerCurrentChange = () => {
  getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
}
const handlerSizeChange = () => {
  getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
}
//品牌修改、删除按钮$row,trademarkId,trademarkName
const editTrademark = async (trademark:saveTrademarkData) => {
  dialogFormVisible.value = true;
  // console.log(trademark);
  isUpdate.value = true;  //进行更新品牌操作
  // dialogFormDate.trademarkName = trademark.tmName;
  // dialogFormDate.trademarkLogo = trademark.logoUrl;
  // dialogFormDate.trademarkId = trademark.id;
  Object.assign(dialogFormDate,trademark);  //此处参数要全部收集带给服务器

}
const deleteTrademark = async (id:number,trademarkName:string) => {
  let res:responseDeleteTrademarkData = await reqRemoveTrademark(id);
  if(res.code == 200){
    getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
    ElMessage({type:'success',message:"品牌" + trademarkName + "移除成功!" });
      // console.log("删除品牌api成功");
  }else{
    ElMessage({type:"error",message:"品牌移除失败!"});
  }
}

//dialog的确定和取消按钮
//向服务器添加一个品牌信息或者更新一个品牌信息
const saveOrUpdateTrademark = async () => {
  //对表单内容进行校验,校验全部通过后，在执行后面的代码，失败后，后面的语句不执行了
  await formRef.value.validate(); //该方法返回的是promise对象 
  if(!isUpdate.value){
    let res:responseSaveTrademarkData = await reqSaveTrademark(dialogFormDate);
    if(res.code == 200){
      //获取更新后的信息
      getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
      ElMessage({type:'success',message:"品牌添加成功!"});
      // console.log("新增品牌api成功",res);
    }else{
      // console.log("新增品牌api失败",res);
      return ElMessage({type:'error',message:"品牌添加失败!"});
    }
  }else{  
    let res:responseSaveTrademarkData = await reqPutTrademark(dialogFormDate);
    if(res.code == 200){
      //获取更新后的信息
      getTrademarkList({page:paginationData.currentPage,limit:paginationData.pageSize});
      ElMessage({type:'success',message:"品牌信息更新成功!"});
      // console.log("更新api成功",res);
    }else{
      // console.log("更新api失败",res);
      return ElMessage({type:'error',message:"品牌信息更新失败!"});
    }
  }
  //清除表单数据
  cancle();
}
//取消按钮
const cancle = () => {
  dialogFormVisible.value = false;
  //表单数据置空
  dialogFormDate.tmName = "";
  dialogFormDate.logoUrl = "";
  dialogFormDate.id = 0;
  //清除dialog表单的校验信息
  formRef.value.clearValidate('tmName');
  formRef.value.clearValidate('logoUrl');
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>